package com.hzy.app.service;

import com.hzy.app.utils.DbUtils;
import com.hzy.common.R;
import com.hzy.common.handler.RoutingContextUtil;
import io.vertx.core.Vertx;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import io.vertx.sqlclient.Tuple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

/**
 * @author huangzhenyu
 * @date 2025/4/4 13:55
 */

public class Test {

    private static final Logger log = LoggerFactory.getLogger(Test.class);


    public static void publishMessage(RoutingContext ctx) {
        Vertx vertx = ctx.vertx();
        vertx.eventBus().request("my.address", RoutingContextUtil.getRequestParams(ctx).getString("message"), res -> {
            if (res.succeeded()) {
                Message<Object> result = res.result();
                Object message = result.body();
                log.info("Received reply: {}", message);
                ctx.response()
                        .end(Json.encode(R.success(message)));
            }
            if (res.failed()) {
                ctx.response()
                        .end(Json.encode(R.error("消息返回异常！" + res.result().body())));
            }
        });
    }

    public static void dbSelect(RoutingContext ctx) {
        DbUtils.query("SELECT * FROM sc_task", HashMap.class)
                .onSuccess(data -> ctx.response()
                        .setStatusCode(200)
                        .end(Json.encode(R.success(data))))
                .onFailure(err -> {
                    log.error(err.getMessage(), err);
                    ctx.fail(err);
                });
    }

    public static void dbRemove(RoutingContext ctx) {
        DbUtils.delete("delete from sc_task where task_id = ?", Tuple.of(ctx.request().getParam("taskId")))
                .onSuccess(data -> ctx.response()
                        .setStatusCode(200)
                        .end(Json.encode(R.success(data.rowCount()))))
                .onFailure(err -> {
                    log.error(err.getMessage(), err);
                    ctx.fail(err);
                });
    }

    public static void selectProduct(RoutingContext ctx) {
        ctx.response().end(new JsonObject().put("productID", ctx.request().getParam("productID")).toString());
    }
}
